<?php
/**
 * Created by PhpStorm.
 * User: lee
 * Date: 2018/3/9
 * Time: 下午3:01
 */

namespace Biz\module\Classes;

use Biz\model\activity\FullShipping as mFullShipping;
use Biz\model\GoodsBasicInfo as mGoodsBasicInfo;
use Biz\model\GoodsSku as mGoodsSku;
use Biz\model\ShopFavorite;
use Biz\model\trade\Cart as mCart;
use Biz\model\trade\CartV as mCartV;
use Biz\module\Classes\Coupon as clsCoupon;
use Biz\module\Classes\ShopCoupon as clsShopCoupon;
use Biz\module\Sys\ErrorConst as beErrorConst;
use Biz\pockets\constInterface\ActivityInfo;
use Biz\pockets\serviceTrait\_Async;
use Biz\service\activity\Coupon as sCoupon;
use Biz\service\activity\FullShipping;
use Biz\service\activity\PinTuan;
use Biz\service\Goods;
use Biz\service\ShippingTempl as sShippingTempl;
use Biz\service\ShopGoodsOperator;
use Biz\service\ShopInfo as sShopInfo;
use Biz\service\Sku as sSku;
use Biz\service\SkuInfo as SkuInfo;
use Biz\service\TipInfo as sTipInfo;
use Biz\tools\Amount;
use Biz\tools\Amount as toolAmount;
use Biz\tools\ThrowException as toolThrowException;
use Doraemon\amqp\Queue as aQueue;
use Doraemon\pockets\constInterface\AppType;
use Doraemon\tools\ActionLog;
use Doraemon\tools\HhzClient;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\Log;
use Doraemon\tools\Log as tLog;
use Doraemon\tools\Sensors;

/**
 * Class Cart
 *
 * @package Biz\module\Classes
 *
 *          此类请不要单独使用，调用购物车，请使用service下面的cart类
 */
final class Cart implements AppType
{
    use _Async;
    private $virtual = false;
    const ERROR_CODE_NOT_ENOUGH = 1;
    const ERROR_CODE_MAX_LIMIT = 2;
    const ERROR_CODE_FORBIDDEN = 3; //不允许显示的文案

    /**
     * 设置游客
     * @return Cart
     */
    public function setVirtual()
    {
        $this->virtual = true;
        return $this;
    }

    /**
     * 从购物车中删除sku
     * @param int $uid 用户/游客id
     * @param array $skuIds 货品id集合
     * @param int $appSource app来源
     * @param string $from 操作来源
     * @param int $toFav 是否加入收藏开关 0 不操作 1 加入收藏
     * @return mixed
     */
    public function delCart($uid, $skuIds, $appSource, $from = 'cart', $toFav = 0)
    {
        //获取购买的数量
        $goodsBuySum = $this->getCartByCondition(
            ['uid' => $uid, 'sku_id' => $skuIds, 'app_source' => $appSource, 'GROUP' => 'goods_id'],
            ['goods_id', 'buy_sum' => \Medoo\Medoo::raw('sum(buy_num)')]
        );

        //指定商品的购物车数据变为删除状态
        $result = $this->delCartSku($uid, $skuIds);

        //异步操作
        if ($from == 'cart') {
            self::_async($uid, $skuIds, $appSource, $toFav, $goodsBuySum);
        }

        return $result;
    }

    /**
     * 从购物车中删除sku,异步操作
     * @param int $uid 用户/游客id
     * @param array $skuIds 货品id集合
     * @param int $appSource app来源
     * @param int $toFav 是否加入收藏开关
     * @param array $goodsBuySum 购物车货品数据
     * @return mixed
     * @throws \Exception
     */
    public static function _async_delCart($uid, $skuIds = [], $appSource = 0, $toFav = 0, $goodsBuySum = [])
    {
        //加入收藏
        if ($toFav == 1 && $uid > 0) {
            $skusInfo = SkuInfo::getSkuList([], $skuIds, false);
            $goodsIds = array_column($skusInfo, "goods_id");
            if ($goodsIds) {
                $is_favorites = ShopFavorite::is_favorited($uid, $goodsIds, ShopFavorite::TYPE_GOODS, $appSource);
                foreach ($is_favorites as $goodsId => $is_favorite) {
                    if (!$is_favorite) {
                        ShopGoodsOperator::favorite($uid, $goodsId, ShopFavorite::TYPE_GOODS, $appSource);
                    }
                }
            }
        }
        //移除购物车的行为日志
        if ($toFav == 0) {
            if (!empty($goodsBuySum)) {
                foreach ($goodsBuySum as $value) {
                    //移除购物车行为日志
                    ActionLog::log($uid, ['spu_id' => $value['goods_id'], 'num' => $value['buy_sum'],], ActionLog::BIZ_REMOVE_CART);
                }
            }
        }
    }

    /**
     * 更改SKU信息
     * @param $uid
     * @param $oldSkuId
     * @param $newSkuId
     * @param $appSource
     * @return array
     * @throws \Exception
     */
    public function changeSku($uid, $oldSkuId, $newSkuId, $appSource = 0)
    {
        //查询修改前的购物车中sku信息
        $oldInfo = $this->getInfoBySkuIdFromMaster($uid, $oldSkuId, $appSource);

        if (empty($oldInfo)) {
            throw new \Exception('非法渠道提交');
        }

        //查询新更换的sku是否在购物车中存在
        $newInfo = $this->getInfoBySkuIdFromMaster($uid, $newSkuId, $appSource);

        $newSkuInfos = sSku::Sku4Order([$newSkuId]);

        if (empty($newSkuInfos)) {
            throw new \Exception('新加商品不存在');
        } else {
            $newSkuInfo = $newSkuInfos[$newSkuId];
        }

        if ($oldInfo['goods_id'] != $newSkuInfo['goods_id']) {
            throw new \Exception('请从正确渠道添加');
        }

        if (!empty($newInfo)) {
            $activeStatus = $this->getCartActiveStatus();
            $delStatus = $this->getCartDelStatus();
            if ($newInfo['status'] != $activeStatus) {

                $this->modifyCart(['status' => $delStatus], ['uid' => $uid, 'sku_id' => $oldSkuId, 'app_source' => $appSource]);

                $upData = [
                    'status' => $activeStatus,
                    'buy_num' => 1,
                ];

                $cartId = $newInfo['id'];

            } else {
                throw new \Exception('此商品在购物车中已存在');
            }

        } else {
            $upData = [
                'sku_id' => $newSkuId,
                'edittime' => '0000-00-00 00:00:00',
            ];

            $cartId = $oldInfo['id'];
        }

        $upData = array_merge($upData, [
            'sku_desc' => $newSkuInfo['sku_desc'],
            'sku_attr' => $newSkuInfo['sku_attr'],
            'sell_price' => $newSkuInfo['ori_price'],
            'buy_price' => $newSkuInfo['actual_price'],
        ]);

        $this->modifyCart($upData, ['id' => $cartId, 'uid' => $uid, 'app_source' => $appSource]);

        $cartSku = self::getCartInfoFromMaster($uid, $newSkuId, $appSource);

        //log
        self::info_log('购物车成功更换sku', [
            'cartId' => $cartId,
            'params' => ['uid' => $uid, 'oldSkuId' => $oldSkuId, 'newSkuId' => $newSkuId],
            'upData' => $upData
        ]);

        return $this->formatActiveSkuInfo($cartSku);
    }

    /**
     * 增减购买数
     * @param int $uid 用户/游客id
     * @param int $skuId 货品id
     * @param int $buyNum 增加/减少数量
     * @param int $currentBuyNum 输入数量
     * @param int $appSource app来源
     * @return mixed
     * @throws \Exception
     */
    public function updateBuyNum($uid, $skuId, $buyNum = 1, $currentBuyNum = 0, $appSource = 0)
    {

        if ($currentBuyNum > 0) {
            $this->modifyCart([
                'buy_num' => 0,
            ], ['uid' => $uid, 'sku_id' => $skuId, 'app_source' => $appSource]);
            $buyNum = $currentBuyNum;
        }

        if ($buyNum == 0) {
            throw new \Exception('请从正确渠道传入数据');
        }

        $result = [];

        //查询sku信息
        $skuInfoArray = sSku::Sku4Order([$skuId]);
        $skuInfo = isset($skuInfoArray[$skuId]) ? $skuInfoArray[$skuId] : [];

        //检查sku是否可以添加到购物车中
        $this->checkSkuCanAddToCart($skuInfo);

        //获取指定SKU的购物车信息
        $cartSku = $this->getInfoBySkuIdFromMaster($uid, $skuId, $appSource);

        //允许购买数量
        $buySum = isset($cartSku['buy_num']) ? $cartSku['buy_num'] + $buyNum : $buyNum;
        $minStock = $this->minStock($skuInfo);
        $currentBuyNum = $buySum > $minStock ? $minStock : $buySum;
        $currentBuyNum = $currentBuyNum > 0 ? $currentBuyNum : 0;

        if (!empty($cartSku)) {
            if ($buySum > $minStock) {
                //需要返回可以加到购物车的数量
                $result['current_buy_num'] = (string)$minStock;
                $tipMsg = '仅剩';
                if ($skuInfo['limit_buy_count']) {
                    if ($buySum > $skuInfo['limit_buy_count']) {
                        $tipMsg = '限购';
                    }
                }
                $result['tip_msg'] = '此商品' . $tipMsg . $minStock . '件';
            }
        }
        $status = $this->getCartActiveStatus();
        $addResult = $this->addCartData($uid, $skuInfo, $appSource, $buyNum, $currentBuyNum, $cartSku, $status);
        $id = $addResult['id'];
        $data = $addResult['data'];

        //成功日志
        self::info_log('成功更新购物车购买数', array_merge([
            'cartId' => $id,
            'params' => [
                'uid' => $uid,
                'sku_id' => $skuId,
                'buy_num' => $buyNum,
                'current_buy_num' => $currentBuyNum,
                'app_source' => $appSource,
            ],
            'upData' => $data
        ]));

        return $result;
    }

    /**
     * 组装基础数据，需要加入购物车数据表的数据
     * @param int $uid 用户/游客id
     * @param array $skuInfo 货品信息
     * @param int $buyNum 增加/减少数量
     * @param int $currentBuyNum 输入数量
     * @param int $appSource app来源
     * @param array $cartSku 购物车已有数据
     * @param int $status 购物车状态
     * @return mixed
     * @throws \Exception
     */
    private function addCartData($uid, $skuInfo, $appSource, $buyNum, $currentBuyNum, $cartSku, $status)
    {
        //组装基础数据，需要加入购物车数据表的数据
        $skuAttr = [];
        if (isset($skuInfo['sku_attr_t1']['id']) && $skuInfo['sku_attr_t1']['id']) {
            array_push($skuAttr, $skuInfo['sku_attr_t1']['id']);
        }
        if (isset($skuInfo['sku_attr_t2']['id']) && $skuInfo['sku_attr_t2']['id']) {
            array_push($skuAttr, $skuInfo['sku_attr_t2']['id']);
        }
        $data = [
            'uid' => $uid,
            'wiki_id' => $skuInfo['goods_info']['wiki_id'],
            'cover_img' => $skuInfo['extend_info'] ?: $skuInfo['goods_info']['spec_img'],
            'title' => $skuInfo['goods_info']['title'],
            'sell_price' => $skuInfo['ori_price'],
            'sku_desc' => $skuInfo['sku_desc'] ? str_replace(' ', ',', $skuInfo['sku_desc']) : '',
            'sku_attr' => $skuAttr ? implode(',', $skuAttr) : '',
            'buy_price' => isset($skuInfo['actual_price']) ? $skuInfo['actual_price'] : $skuInfo['ori_price'],
            'app_source' => $appSource,
            'status' => $status,
        ];
        if (empty($cartSku)) {
            //没有加购的商品
            $data['sku_id'] = $skuInfo['sku_id'];
            $data['goods_id'] = $skuInfo['goods_id'];
            $data['shop_id'] = $skuInfo['shop_id'];
            $data['buy_num'] = $buyNum;
            $data['addtime'] = date('Y-m-d H:i:s');
            $this->addCart($data);
            $id = $this->getAddCartId();
            if (empty($id)) {
                self::log('用户加购物车失败', [
                    'uid' => $uid,
                    'sku_id' => $skuInfo['sku_id'],
                    'buy_num' => $buyNum,
                    'sql' => $this->getCartLog(),
                ]);
                //添加购物车失败的微信通知通知
                aQueue::insertQueue("queue/Wechatnotice/toTag", [
                    "totag" => \Biz\pockets\constInterface\BizWechatTagConfig::TAG_BIZ_RD_SYSTEM,
                    "content" => vsprintf('添加购物车失败,info=%s %s %s %s %s', [
                        $uid,
                        $skuInfo['sku_id'],
                        $buyNum,
                        json_encode($data, JSON_UNESCAPED_UNICODE),
                    ])
                ], aQueue::QUEUE_BIZ);

                throw new \Exception('添加购物车失败');
            }
        } else {
            //已经加购的商品
            //如果该商品在购物车中是删除状态，则需要更新其他信息
            $delStatus = $this->getCartDelStatus();
            $activeStatus = $this->getCartActiveStatus();
            $data['buy_num'] = $currentBuyNum;

            if ($cartSku['status'] == $delStatus) {
                $data['addtime'] = date('Y-m-d H:i:s');
                $data['edittime'] = '0000-00-00 00:00:00';
                $data['status'] = $activeStatus;
            } else {
                $data['edittime'] = date('Y-m-d H:i:s');

                //如果计算出的购买数=0，则自动变更该SKU状态
                if ($data['buy_num'] == 0) {
                    $data['status'] = $delStatus;
                }
            }

            $id = $cartSku['id'];
            $this->modifyCart($data, ['id' => $id]);
        }
        return compact('id', 'data');
    }


    /**
     * 游客购物车进入用户购物车
     * @param int $vid 游客id
     * @param int $uid 用户id
     * @param int $appSource app来源
     * @return mixed
     * @throws \Exception
     */
    public function cartvToCart($vid, $uid, $appSource = 0)
    {

        $cartvList = mCartV::select('*', ['uid' => $vid, 'app_source' => $appSource, 'status[!]' => mCart::STATUS_DELETE]);

        if (empty($cartvList)) {
            return true;
        }

        //登录用户的购物车里商品数
        $cartSum = mCart::count(['uid' => $uid, 'app_source' => $appSource, 'status[!]' => mCart::STATUS_DELETE]);

        if ($cartSum == mCart::ITEM_TOTAL_SUM) {
            return true;
        }

        $cartVSum = count($cartvList);

        tLog::cart_cartvtocart_info('购物车合并前的debug',
            ['vid' => $vid, 'uid' => $uid, 'cartvsum' => $cartVSum, 'cartsum' => $cartSum]);

        if (($cartVSum + $cartSum) > mCart::ITEM_TOTAL_SUM) {
            return true;
        }

        $data = array_map(function ($v) use ($uid) {

            unset($v['id']);

            $v['uid'] = $uid;

            return $v;
        }, $cartvList);

        mCart::insert($data);


        return true;
    }

    /**
     * @desc 购物车统计数量
     * @param $uid
     * @param $appSource
     * @return array
     */
    public function totalSum($uid, $appSource)
    {
        $data = [];
        $delStatus = $this->getCartDelStatus();
        $data['sku_sum'] = $this->getCartCount(['uid' => $uid, 'app_source' => $appSource, 'status[!]' => $delStatus]);
        return $data;
    }


    protected function formatCartList($uid, &$data, $isSelect, $areaCode, $appSource, $appType, $groupMap)
    {
        //节选标识
        $isParagraph = $appSource == AppType::APPTYPE_PARAGRAPH_MINIPROGRAM;
        $isMini = $appType == AppType::APPTYPE_MINIPROGRAM;
        foreach ($data['list'] as $shopId => &$cartInfo) {

            foreach ($cartInfo['sku_list'] as $key => $cartSku) {
                $skuCartFormat = $this->formatActiveSkuInfo($cartSku);
                $skuId = $skuCartFormat['sku_id'];

                //计算购物车总信息
                if ($isSelect) {
                    $data['summary']['total_buynum'] += $cartSku['buy_num'];
                    $data['summary']['goods_amount'] += $skuCartFormat['buy_price'] * $cartSku['buy_num'];


                    //计算店铺中商品购买的运费使用
                    $shippingPriceParams[$shopId][$cartSku['goods_id']][$skuId]['shipping_templ_id'] = $cartSku['sku_info']['goods_info']['shipping_templ_id'];
                    @$shippingPriceParams[$shopId][$cartSku['goods_id']][$skuId]['buy_num'] += $cartSku['buy_num'];
                    @$shippingPriceParams[$shopId][$cartSku['goods_id']][$skuId]['weight'] += $cartSku['sku_info']['weight'];
                    @$shippingPriceParams[$shopId][$cartSku['goods_id']][$skuId]['volume'] += $cartSku['sku_info']['volume'];

                    //计算购物车中商家总信息
                    $data['list'][$shopId]['summary']['goods_amount'] += $skuCartFormat['buy_price'] * $cartSku['buy_num'];

                    //计算优惠券优惠使用
                    $skuBuyList[$shopId][$skuCartFormat['sku_id']] = [
                        'goods_id' => $skuCartFormat['goods_id'],
                        'buy_price' => $skuCartFormat['buy_price'],
                        'buy_num' => $cartSku['buy_num']
                    ];
                }


                //SKU排序用
                $skuAddTimeSort[$shopId][] = $cartSku['addtime_stamp'];

                $cartInfo['sku_list'][$key] = $skuCartFormat;
            }

            //计算购物车中最值得店铺优惠券，会改变商家结构中的goods_amount金额和总结构中的goods_amount金额
            //购物车平台优惠券计算  小程序不可用

            if (version_compare(HhzClient::getClientVersion(), '3.6.0', '>=')) {

                if (isset($skuBuyList) && $uid > 0 && !$isParagraph && !$isMini) {
                    self::calShopCouponSelect($uid, $shopId, $data, $skuBuyList[$shopId]);
                }
            }


            //格式化数据
            $data['list'][$shopId]['summary']['goods_amount'] = toolAmount::format($data['list'][$shopId]['summary']['goods_amount']);


            //计算店铺中商品购买的运费
            if (isset($shippingPriceParams[$shopId])) {

                $shippingPrice = sShippingTempl::getShippingFee($shopId,
                    $shippingPriceParams[$shopId], $areaCode);
                $data['list'][$shopId]['summary']['shipping_price'] = $shippingPrice['price'];
            }

            //商品按照sku添加到购物车的时间倒序
            if (isset($skuAddTimeSort[$shopId])) {

                array_multisort($skuAddTimeSort[$shopId], SORT_DESC, $data['list'][$shopId]['sku_list']);

                rsort($skuAddTimeSort[$shopId]);

                $data['list'][$shopId]['sort_near_addtime'] = $skuAddTimeSort[$shopId][0];

            }

            if (!empty($data['list'][$shopId]['sku_list'])) {
                //商品tip信息
                sTipInfo::skuInCart($data['list'][$shopId]['sku_list']);

                //商品套餐信息
                sTipInfo::mealTip($data['list'][$shopId]['sku_list']);

                //收货地址限制提示
                sTipInfo::areaTip($data['list'][$shopId]['sku_list'], $areaCode);

                //团购提示
                sTipInfo::groupTip($data['list'][$shopId]['sku_list'], $groupMap);
            }

        }

        if (!empty($data['list'])) {
            //商家tip信息
            sTipInfo::shopInCart($data['list'], $areaCode, $isSelect);


            //商家按照sku添加到购物车的时间倒序
            $data['list'] = array_values($data['list']);

            array_walk($data['list'], function (&$v) use (&$skuAddTimeShopSort) {
                $skuAddTimeShopSort[] = $v['sort_near_addtime'];

                unset($v['sort_near_addtime']);
            });

            array_multisort($skuAddTimeShopSort, SORT_DESC, $data['list']);

        }

        //购物车平台优惠券计算  小程序不可用
        if (version_compare(HhzClient::getClientVersion(), '3.5.2', '>=')) {
            if (isset($skuBuyList) && $uid > 0 && !$isParagraph && !$isMini) {
                $dataBuyList = [];
                foreach ($skuBuyList as $shopId => $shopBuyList) {
                    foreach ($shopBuyList as $skuId => $buyList) {
                        $dataBuyList[$skuId] = $buyList;
                    }
                }

                self::calCouponSelect($uid, $data, $dataBuyList);
            }
        }


        //格式化保留两位小数
        $data['summary']['goods_amount'] = Amount::format($data['summary']['goods_amount']);


    }

    protected static function calCouponSelect($uid, &$data, $skuBuyList)
    {

        $couponSelect = clsCoupon::getBestCouponSelect($uid, $skuBuyList);

        if (!empty($couponSelect)) {
            //优惠总额递减
            $data['summary']['goods_amount'] = $data['summary']['goods_amount'] - $couponSelect['detract_amount'];


            $data['coupon'] = [
                'coupon_vid' => $couponSelect['coupon_vid'],
                'coupon_id' => $couponSelect['coupon_id'],
                'title' => $couponSelect['title'],
                'detract_amount' => $couponSelect['detract_amount'],
            ];
        } else {
            $data['coupon'] = null;
        }


    }

    protected static function calShopCouponSelect($uid, $shopId, &$data, &$skuBuyList)
    {
        $couponSelect = clsShopCoupon::getBestShopCouponSelect($uid, $shopId, $skuBuyList);

        if (!empty($couponSelect)) {


            //店铺最值优惠券拿到后开始计算剩余的商品购买额
            $result = clsShopCoupon::calOrderSkuCouponDiscount($uid, $couponSelect['coupon_id'],
                $couponSelect['detract_amount'], '', $skuBuyList);

            if (!empty($result)) {
                foreach ($skuBuyList as $skuId => &$skuBuyInfo) {
                    $skuBuyInfo['total_amount'] = ($skuBuyInfo['buy_num'] * $skuBuyInfo['buy_price']) - $result[$skuId]['coupon_discount'];
                }
            }

            //总额递减
            $data['list'][$shopId]['summary']['goods_amount'] = $data['list'][$shopId]['summary']['goods_amount'] - $couponSelect['detract_amount'];

            $data['summary']['goods_amount'] = $data['summary']['goods_amount'] - $couponSelect['detract_amount'];

            $data['summary']['s_coupon_amount'] = Amount::format($data['summary']['s_coupon_amount'] + $couponSelect['detract_amount']);
        }
    }

    protected function getCartInfoFromMaster($uid, $skuId, $appSource)
    {
        $cartSku = $this->getInfoBySkuIdFromMaster($uid, $skuId, $appSource);

        if ($cartSku) {
            $skuInfos = sSku::Sku4Order([$skuId]);
            $cartSku['sku_info'] = $skuInfos[$skuId];
        }

        return $cartSku;
    }


    /**
     * 判断一个sku是否可以添加到购物车中
     * @param $skuInfo
     * @param $code
     * @throws \Exception
     */
    protected function checkSkuCanAddToCart($skuInfo, $code = 0)
    {
        //判断该SKU是否存在
        if (empty($skuInfo)) {
            toolThrowException::main(beErrorConst::ERROR_SKU_DOESNOT_EXISTS);
        }

        //商品SKU和商品状态
        if (!mGoodsBasicInfo::checkCanBuy($skuInfo['goods_info']['status'])) {
//            toolThrowException::main(beErrorConst::ERROR_GOODS_STATUS_ERROR);
            throw new \Exception('该SKU不是上架状态,skuInfo:' . json_encode($skuInfo, JSON_UNESCAPED_UNICODE), self::ERROR_CODE_FORBIDDEN);
        }

        if ($skuInfo['status'] == mGoodsSku::STATUS_DELETE) {
            throw new \Exception('该SKU已被删除,skuInfo:' . json_encode($skuInfo, JSON_UNESCAPED_UNICODE), self::ERROR_CODE_FORBIDDEN);
        }

        $minStock = $this->minStock($skuInfo);

        //判断该SKU基础库存是否充足
        if ($minStock <= 0) {
            throw new \Exception('该商品库存不足', $code);
        }
    }

    /**
     * 购物车列表
     * @param int $uid 用户/游客id
     * @param mixed $status 购物车状态
     * @param array $skuIds 货品id集合
     * @param int $appSource app来源
     * @return mixed
     */
    protected function getCartListMain($uid, $status, $skuIds = [], $appSource = 0)
    {
        $where = ['uid' => $uid, 'status' => $status, 'app_source' => $appSource, 'ORDER' => ['addtime' => 'DESC']];
        if (!empty($skuIds)) {
            $where['sku_id'] = $skuIds;
        }
        return $this->getCartByCondition($where, '*');
    }

    protected function getCartFailList($uid, $skuIds = [], $withInfo = true, $appSource = 0)
    {
        $status = $this->getCartFailStatus();
        $list = $this->getCartListMain($uid, $status, $skuIds, $appSource);
        $response = [];
        if (!empty($list)) {
            if ($withInfo) {
                $skuIdList = array_column($list, 'sku_id');
                $skuInfoList = sSku::Sku4Order($skuIdList);
            }

            foreach ($list as $info) {
                $this->formatInfo($info);
                if (isset($skuInfoList) && isset($skuInfoList[$info['sku_id']])) {
                    $info['sku_info'] = $skuInfoList[$info['sku_id']];
                }
                $response[$info['sku_id']] = $info;
                unset($info);
            }
        }
        return $response;
    }

    protected function getCartActiveList($uid, $skuIds, $releatWith = true, $appSource = 0)
    {
        $status = $this->getCartActiveStatus();
        $list = $this->getCartListMain($uid, $status, $skuIds, $appSource);
        $response = [];
        if (!empty($list)) {
            if ($releatWith) {
                $skuIdList = array_column($list, 'sku_id');
                $skuInfoList = sSku::Sku4Order($skuIdList);
                //            $skuInfoList = sSkuInfo::getSkusInfoByIds($skuIdList);
            }

            foreach ($list as $info) {
                $this->formatInfo($info);
                if (isset($skuInfoList) && isset($skuInfoList[$info['sku_id']])) {
                    $info['sku_info'] = $skuInfoList[$info['sku_id']];
                }
                $response[$info['shop_id']][] = $info;
                unset($info);
            }
        }
        return $response;
    }

    /**
     * @desc 购物车失效sku格式
     * @param $cartSku
     * @return array
     */
    protected function formatFailCartSku($cartSku)
    {
        return [
            'sku_id' => $cartSku['sku_id'],
            'goods_id' => $cartSku['goods_id'],
            'title' => $cartSku['title'],
            'sku_desc' => $cartSku['sku_desc'],
            'cover_img' => strlen($cartSku['cover_img']) > 30 ? $cartSku['cover_img'] : ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ,
                $cartSku['cover_img'], ImgUrl::IMAGE_SIZE_SQ_THUMB)
        ];

    }

    protected function formatActiveSkuInfo(&$cartSku)
    {
//        $minStock = $this->minStock($cartSku['sku_info'],$promoInfo);
        //预售状态
        $prepare_status = 0;
        if($cartSku && is_array($cartSku)) {
            if(isset($cartSku['sku_info']['activity_start_time']) && strtotime($cartSku['sku_info']['activity_start_time']) > time() && isset($cartSku['sku_info']['preview_start_time']) && strtotime($cartSku['sku_info']['preview_start_time']) < time()) {
                $prepare_status = 1;
            }
        }
        $data = [
            'sku_id' => $cartSku['sku_id'],
            'goods_id' => $cartSku['goods_id'],
            'wiki_id' => $cartSku['wiki_id'],
            'title' => $cartSku['title'],
            'cover_img' => ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $cartSku['sku_info']['spec_img'] ?: $cartSku['cover_img'], ImgUrl::IMAGE_SIZE_SQ_THUMB),
            'sku_desc' => $cartSku['sku_desc'],
            'sku_params' => [],
            'sell_price' => $cartSku['sku_info']['ori_price'],
            'o_buy_price' => $cartSku['buy_price'],
            'buy_price' => $cartSku['sku_info']['actual_price'], // 0 sell_price 原价 a buy_price 当前价
            'buy_num' => $cartSku['buy_num'],
            'stock' => $cartSku['sku_info']['actual_stock'],
            'ori_price' => $cartSku['sku_info']['ori_price'],
            'actual_price' => $cartSku['sku_info']['actual_price'],
            'shipping_templ_id' => $cartSku['sku_info']['goods_info']['shipping_templ_id'],
            'active_icon_list' => isset($cartSku['active_icon_list']) ? $cartSku['active_icon_list'] : [],
            'activity_type' => isset($cartSku['sku_info']['activity_type']) ? $cartSku['sku_info']['activity_type'] : null,
            'preview_start_time' => isset($cartSku['sku_info']['preview_start_time']) ? $cartSku['sku_info']['preview_start_time'] : null,
            'activity_start_time' => isset($cartSku['sku_info']['activity_start_time']) ? $cartSku['sku_info']['activity_start_time'] : null,
            'activity_end_time' => isset($cartSku['sku_info']['activity_end_time']) ? $cartSku['sku_info']['activity_end_time'] : null,
            'activity_prepare_status' => $prepare_status
        ];

        $data['has_promotion'] = ($data['o_buy_price'] < $data['buy_price']) ? 1 : 0;

//        tLog::debug('cart_sku_list', ["cartSku" => $cartSku]);

        if ($cartSku['sku_info']['sku_attr_t1'] && isset($cartSku['sku_info']['sku_attr_t1']['id'])) {
            $data['sku_params']['t1'] = $cartSku['sku_info']['sku_attr_t1']['id'];
        }
        if ($cartSku['sku_info']['sku_attr_t2'] && isset($cartSku['sku_info']['sku_attr_t2']['id'])) {
            $data['sku_params']['t2'] = $cartSku['sku_info']['sku_attr_t2']['id'];
        }

        if (!empty($promoInfo)) {
            $data['promo_info'] = $promoInfo;
        }

        return $data;
    }

    /**
     * 切换购物车有效与失效的状态
     * @param int $uid 游客id
     * @param array $skuInfo 货品信息
     * @param int $appSource app来源
     * @param int $flag 1 变为有效 0 变为失效
     * @return mixed
     * @throws \Exception
     */
    protected function toggleStatus($uid, $skuInfo, $appSource, $flag = 1)
    {
        try {
            $this->isFailSku($skuInfo);
            $isFail = false;
            $message = '';
        } catch (\Exception $e) {
            $isFail = true;
            $message = $e->getMessage();
        }

        $isChange = false;
        $status = null;
        $title = null;
        if ($flag > 0 && $isFail == false) {
            $status = $this->getCartActiveStatus();
            $title = '购物车SKU由失效变为有效';
            $isChange = true;
        }
        if ($flag == 0 && $isFail == true) {
            $status = $this->getCartFailStatus();
            $title = '购物车SKU由有效变为失效,原因:' . $message;
            $isChange = true;
        }
        if ($isChange) {
            $data = $this->modifyCart(['status' => $status], ['uid' => $uid, 'sku_id' => $skuInfo['sku_id'], 'app_source' => $appSource]);
            self::info_log($title, ['uid' => $uid, 'sku_id' => $skuInfo['sku_id'], 'app_source' => $appSource, 'sku_info' => $skuInfo]);

            if ($data->rowCount() == 1) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取货品可购买数量
     * @param array $skuInfo 货品信息
     * @return int
     */
    protected function minStock($skuInfo)
    {
        $stock = isset($skuInfo['actual_stock']) ? $skuInfo['actual_stock'] : $skuInfo['stock'];
        if ($skuInfo['limit_buy_count']) {
            $minStock = $skuInfo['limit_buy_count'];
            if($stock == 0) {
                $minStock = 0;
            }
            return $minStock;
        }
        return $stock;
    }

    /**
     * @desc 判断SKU，是否符合购物车失效商品的规则
     * @param $skuInfo
     * @throws \Exception
     */
    protected function isFailSku($skuInfo)
    {
        if ($skuInfo['status'] == mGoodsSku::STATUS_DELETE) {
            throw new \Exception('购物车SKU由于SKU状态被删除，变为无效');
        }

        if ($skuInfo['goods_info']['status'] != mGoodsBasicInfo::STATUS_APP_NOMAL) {
            throw new \Exception('购物车SKU由于GOODS下架，变为无效');
        }

        $minStock = $this->minStock($skuInfo);
        if ($minStock == 0) {
            throw new \Exception('购物车SKU由于库存为0，变为无效');
        }

        $versionBool465 = version_compare(HhzClient::getClientVersion(), '4.6.5', '>=');
        if($versionBool465 ) {
            if($skuInfo['activity_type'] != '10' || strtotime($skuInfo['activity_end_time']) < time() || strtotime($skuInfo['preview_start_time']) > time()) {
                throw new \Exception('购物车SKU由于不属于住友津贴活动预售或正在售卖的sku，变为无效');
            }else {
                return true;
            }
        }
    }

    /**
     * 购物车错误日志
     * @param string $title 日志标识
     * @param array $params 存储数据
     */
    private static function log($title, $params)
    {
        tLog::cart_basic_warning('购物车错误日志::' . $title, $params);
    }

    /**
     * 购物车信息日志
     * @param string $title 日志标识
     * @param array $params 存储数据
     */
    private static function info_log($title, $params)
    {
        tLog::cart_basic_info('购物车信息日志::' . $title, $params);
    }

    /**
     * 购物车中商品购买限制
     * @param int $uid 用户id
     * @param int $skuId 货品id
     * @param int $appSource app来源
     * @return mixed
     */
    private function getInfoBySkuIdFromMaster($uid, $skuId, $appSource)
    {
        if ($this->virtual) {
            return mCartV::getInfoBySkuIdFromMaster($uid, $skuId, $appSource);
        } else {
            return mCart::getInfoBySkuIdFromMaster($uid, $skuId, $appSource);
        }
    }

    /**
     * 获取购物车中有效商品的数量
     * @param int $uid 用户id
     * @param int $appSource app来源
     * @return mixed
     */
    private function getActiveSkuTotalBuyNum($uid, $appSource)
    {
        if ($this->virtual) {
            return mCartV::getActiveSkuTotalBuyNum($uid, $appSource);
        } else {
            return mCart::getActiveSkuTotalBuyNum($uid, $appSource);
        }
    }

    /**
     * 获取购物车删除状态
     * @return mixed
     */
    private function getCartDelStatus()
    {
        return $this->virtual ? mCartV::STATUS_DELETE : mCart::STATUS_DELETE;
    }

    /**
     * 获取购物车有效状态
     * @return mixed
     */
    private function getCartActiveStatus()
    {
        return $this->virtual ? mCartV::STATUS_ACTIVE : mCart::STATUS_ACTIVE;
    }

    /**
     * 获取购物车失效状态
     * @return mixed
     */
    private function getCartFailStatus()
    {
        return $this->virtual ? mCartV::STATUS_FAIL : mCart::STATUS_FAIL;
    }

    /**
     * 购物车中商品购买限制
     * @return mixed
     */
    private function getTotalSum()
    {
        return $this->virtual ? mCartV::ITEM_TOTAL_SUM : mCart::ITEM_TOTAL_SUM;
    }

    /**
     * 添加购物车数据
     * @param array $info
     * @return mixed
     */
    private function formatInfo(&$info)
    {
        return $this->virtual ? mCartV::formatInfo($info) : mCart::formatInfo($info);
    }

    /**
     * 查询购物车数据
     * @param mixed $fields 字段
     * @param array $condition 查询条件
     * @return mixed
     */
    private function getCartByCondition($condition, $fields = '*')
    {
        return $this->virtual ? mCartV::select($fields, $condition) : mCart::select($fields, $condition);
    }

    /**
     * 修改购物车数据
     * @param array $data 修改数据
     * @param array $condition 修改条件
     * @return mixed
     */
    private function modifyCart($data, $condition)
    {
        return $this->virtual ? mCartV::update($data, $condition) : mCart::update($data, $condition);
    }

    /**
     * 删除购物车数据
     * @param int $uid
     * @param array $skuIds
     * @return mixed
     */
    private function delCartSku($uid, $skuIds)
    {
        return $this->virtual ? mCartV::delSku($uid, $skuIds) : mCart::delSku($uid, $skuIds);
    }

    /**
     * 添加购物车数据
     * @param array $data
     * @return mixed
     */
    private function addCart($data)
    {
        return $this->virtual ? mCartV::insert($data) : mCart::insert($data);
    }

    /**
     * 获取购物车数量
     * @param array $condition 修改条件
     * @return mixed
     */
    private function getCartCount($condition)
    {
        return $this->virtual ? mCartV::count($condition) : mCart::count($condition);
    }

    /**
     * 获取插入购物车时的自增id
     * @return mixed
     */
    private function getAddCartId()
    {
        return $this->virtual ? mCartV::id() : mCart::id();
    }

    /**
     * 获取购物车的数据操作日志
     * @return mixed
     */
    private function getCartLog()
    {
        return $this->virtual ? mCartV::log() : mCart::log();
    }

    /**
     * 用户/游客添加购物车流程
     * @param int $uid 用户id
     * @param int $skuIds 货品id集合
     * @param int $buyNum 加购数量
     * @param int $appSource app来源
     * @return mixed
     * @throws \Exception
     */
    public function addToCart($uid, $skuIds, $buyNum, $appSource)
    {
        if ($buyNum <= 0) {
            throw new \Exception('请从正确渠道传入数据');
        }

        $skuList = explode(',', $skuIds);
        foreach ($skuList as $key => $v) {
            $skuList[$key] = trim($v);
            if (!strlen($skuList[$key])) {
                unset($skuList[$key]);
            }
        }

        //查询sku信息
        $skuInfoArray = sSku::Sku4Order($skuList);

        //遍历处理
        $message = '';
        $errorMsg = '';
        $notEnough = 0;
        $totalBuyNum = 0;
        $totalSum = 0;
        $multiple = count($skuList);
        if (!$skuList) {
            throw new \Exception('请从正确渠道传入数据');
        }

        foreach ($skuList as $skuId) {
            $skuInfo = isset($skuInfoArray[$skuId]) ? $skuInfoArray[$skuId] : [];
            $id = 0;
            $cartSku = [];
            $data = [];
            $isBuyLog = true;
            try {
                //获取指定SKU的购物车信息
                $cartSku = $this->getInfoBySkuIdFromMaster($uid, $skuId, $appSource);

                //检查sku是否可以添加到购物车中
                $this->checkSkuCanAddToCart($skuInfo, self::ERROR_CODE_NOT_ENOUGH);

                //允许购买数量
                $skuBuySum = isset($cartSku['buy_num']) ? $cartSku['buy_num'] + $buyNum : $buyNum;
                $minStock = $this->minStock($skuInfo);
                $currentBuyNum = $skuBuySum > $minStock ? $minStock : $skuBuySum;
                $currentBuyNum = $currentBuyNum > 0 ? $currentBuyNum : 0;

                //获取购物车中购买商品的总数
                $totalBuyNum = $this->getActiveSkuTotalBuyNum($uid, $appSource);

                //购物车中商品最大数
                $totalSum = $this->getTotalSum();
                if ($totalBuyNum + 1 > $totalSum) {
                    throw new \Exception('购物车已满，不能加入', self::ERROR_CODE_MAX_LIMIT);
                }

                //组装基础数据，需要加入购物车数据表的数据
                $status = $this->getCartActiveStatus();
                $addResult = $this->addCartData($uid, $skuInfo, $appSource, $skuBuySum, $currentBuyNum, $cartSku, $status);
                $id = $addResult['id'];
                $data = $addResult['data'];
            } catch (\Exception $e) {
                if ($multiple > 1 && ($e->getCode() == self::ERROR_CODE_NOT_ENOUGH)) {
                    //批量错误处理
                    $notEnough++;

                    //组装基础数据，需要加入购物车数据表的数据
                    $status = $this->getCartFailStatus();
                    $addResult = $this->addCartData($uid, $skuInfo, $appSource, $buyNum, $currentBuyNum = $buyNum, $cartSku, $status);
                    $id = $addResult['id'];
                    $data = $addResult['data'];
                } else if ($multiple > 1 && ($e->getCode() == self::ERROR_CODE_MAX_LIMIT)) {
                    $errorMsg = vsprintf('购物车已满，请先删除购物车中的%s件商品', [$totalSum - $totalBuyNum]);
                    $isBuyLog = false;
                    break;
                } else {
                    $isBuyLog = false;
                    throw new \Exception($e->getMessage(), $e->getCode());
                }
            } finally {
                if ($isBuyLog) {
                    //加购行为日志
                    ActionLog::log($uid, [
                        'spu_id' => $skuInfo['goods_id'],
                        'sku_id' => $skuId,
                        'buy_price' => $data['buy_price'],
                        'num' => $buyNum,
                        'first_add_cart' => empty($cartSku) ? 1 : 0
                    ], ActionLog::BIZ_ADD_CART);

                    //神策加购行为日志
                    Sensors::track($uid, ['spu_id' => $skuInfo['goods_id'], 'sku_id' => $skuId, 'buy_price' => $data['buy_price']], Sensors::ADD_CART);

                    //成功日志
                    self::info_log('成功加入购物车', array_merge([
                        'cartId' => $id,
                        'params' => [
                            'uid' => $uid,
                            'sku_id' => $skuId,
                            'buy_num' => $buyNum,
                            'app_source' => $appSource,
                        ],
                        'upData' => $data
                    ]));
                }
            }
        }
        if ($notEnough > 0) {
            $errorMsg = vsprintf('%s件商品已加入购物车，其中%s件商品暂时缺货。', [$multiple - $notEnough, $notEnough]);
        }

        return strlen($errorMsg) > 0 ? $errorMsg : $message;
    }

    /**
     * 购物车列表
     * @param int $uid 用户/游客id
     * @param array selectSkuIds 货品id集合
     * @param string $areaCode 地区编码
     * @param int $appSource app来源
     * @param int $appType app类型
     * @return mixed
     * @throws \Exception
     */
    public function cartListVersion($uid, $selectSkuIds = [], $areaCode = '', $appSource = 0, $appType = 0)
    {
        //debug
        $shopShippingMap = [];
        $shopCouponSelect = [];
        $platformCouponSelect = [];
        $skuBuyList = [];
        //初始化返回结果
        $goods_amount = 0;
        $total_buynum = 0;
        $s_coupon_amount = 0;
        $fail = [];
        $responseList = [
            [
                'summary' => [
                    'goods_amount' => 0,
                    'shipping_price' => 0,
                ],
                'shop_info' => [

                ],
                'coupon_info' => [

                ],
                'sku_list' => [

                ],
            ],
        ];
        $coupon = null;
        $response = [
            'new' => HhzClient::getClientVersion(),
            'summary' => [
                'goods_amount' => &$goods_amount,
                'total_buynum' => &$total_buynum,
                's_coupon_amount' => &$s_coupon_amount,//店铺优惠券最大抵扣金额
            ],
            'list' => &$responseList,
            'fail' => &$fail,
            'coupon' => &$coupon,
        ];

        //判断是否是手选
        $isSelect = !empty($selectSkuIds) ? true : false;

        //获取有效/失效的购物车数据
        $failStatus = $this->getCartFailStatus();
        $activeStatus = $this->getCartActiveStatus();
        $list = $this->getCartListMain($uid, [$failStatus, $activeStatus], [], $appSource);
        $sku_ids = $list ? array_column($list, 'sku_id') : [];
        $goods_ids = $list ? array_column($list, 'goods_id') : [];
        $statusMap = $list ? array_column($list, 'status', 'sku_id') : [];

        //商品详情
        $skuInfoList = sSku::Sku4Order($sku_ids);

        $goods = Goods::Goods($goods_ids, Goods::FIELDS_GROUP_CART);
        $active_icon_map = $goods ? array_column($goods, 'active_icon_list', 'id') : [];

        //查询团购信息
        $groupMap = PinTuan::getCurrentList($goods_ids);
        $responseList = [];
        if (!empty($list)) {
            $activeList = [];
            foreach ($list as $cartSku) {
                $sku_id = $cartSku['sku_id'];
                $skuInfo = isset($skuInfoList[$sku_id]) ? $skuInfoList[$sku_id] : [];
                $initialStatus = isset($statusMap[$sku_id]) ? $statusMap[$sku_id] : $failStatus;
                $shopId = isset($skuInfo['shop_id']) ? $skuInfo['shop_id'] : 0;

                //实时观察失效商品SKU，如果变成有效的，则rollback 到有效列表
                $flag = $initialStatus == $activeStatus ? 0 : 1;
                $toggle = $this->toggleStatus($uid, $skuInfo, $appSource, $flag);
                $activeBool = $initialStatus == $activeStatus && !$toggle;//有效商品,没有变化
                $failBool = $initialStatus == $failStatus && $toggle;//失效商品,有变化
                if ($activeBool || $failBool) {
                    //购物车有效数据,按店铺进行分组
                    $this->formatInfo($cartSku);
                    if (isset($skuInfoList) && isset($skuInfoList[$sku_id])) {
                        $cartSku['sku_info'] = $skuInfoList[$sku_id];
                    }
                    $activeList[$shopId][] = $cartSku;
                } else {
                    $fail[] = $this->formatFailCartSku($cartSku);
                }
            }

            //处理购物车有效数据
            if ($activeList) {
                $isParagraph = $appSource == AppType::APPTYPE_PARAGRAPH_MINIPROGRAM;//节选标识
                $isMini = $appType == AppType::APPTYPE_MINIPROGRAM;//小程序
                foreach ($activeList as $shopId => $shopGoods) {
                    //购物车商家总信息
                    $summary = [
                        'goods_amount' => 0,
                        'shipping_price' => 0,
                    ];
                    $shopInfo = sShopInfo::getShopInfo($shopId, ['user']);

                    //店铺基本信息结构
                    $shop_info = [
                        'shop_id' => $shopInfo['shop_id'],
                        'shop_name' => $shopInfo['shop_name'],
                        'status' => $shopInfo['status'],
                        'imgurl' => $shopInfo['shop_imgurl_small'],
                        'shop_icon' => $shopInfo['shop_imgurl_small'],
                    ];

                    //店铺是否有优惠券结构
                    $coupon_info = [
                        'has_coupon' => clsShopCoupon::checkShopHasCoupon($shopId),
                    ];

                    //店铺商品列表
                    $sku_list = [];
                    $activity_sku_list = [];
                    $shopSkuBuyList = [];
                    $skuAddTimeSort = [];
                    $shippingPriceParams = [];

                    if (empty($selectSkuIds)) {
                        $isReturn = true;
                    } else {
                        $isReturn = false;
                    }
                    foreach ($shopGoods as $cartSku) {
                        $skuCartFormat = $this->formatActiveSkuInfo($cartSku);

                        //计算购物车总信息
                        if (in_array($cartSku['sku_id'], $selectSkuIds)) {
                            $isReturn = true;
                            $total_buynum += $cartSku['buy_num'];
                            $goods_amount += $skuCartFormat['buy_price'] * $cartSku['buy_num'];

                            //计算店铺中商品购买的运费使用
                            if (isset($shippingPriceParams[$cartSku['goods_id']][$cartSku['sku_id']])) {
                                $shippingPriceParams[$cartSku['goods_id']][$cartSku['sku_id']]['buy_num'] += $cartSku['buy_num'];
                                $shippingPriceParams[$cartSku['goods_id']][$cartSku['sku_id']]['weight'] += $cartSku['sku_info']['weight'];
                                $shippingPriceParams[$cartSku['goods_id']][$cartSku['sku_id']]['volume'] += $cartSku['sku_info']['volume'];
                            } else {
                                $shippingPriceParams[$cartSku['goods_id']][$cartSku['sku_id']]['shipping_templ_id'] = $cartSku['sku_info']['goods_info']['shipping_templ_id'];
                                $shippingPriceParams[$cartSku['goods_id']][$cartSku['sku_id']]['buy_num'] = $cartSku['buy_num'];
                                $shippingPriceParams[$cartSku['goods_id']][$cartSku['sku_id']]['weight'] = $cartSku['sku_info']['weight'];
                                $shippingPriceParams[$cartSku['goods_id']][$cartSku['sku_id']]['volume'] = $cartSku['sku_info']['volume'];
                            }


                            //计算购物车中商家总信息
                            $summary['goods_amount'] += $skuCartFormat['buy_price'] * $cartSku['buy_num'];

                            //计算优惠券优惠使用
                            $tempList = [
                                'goods_id' => $skuCartFormat['goods_id'],
                                'buy_price' => $skuCartFormat['buy_price'],
                                'buy_num' => $cartSku['buy_num']
                            ];
                            $skuBuyList[$skuCartFormat['sku_id']] = $tempList;
                            $shopSkuBuyList[$skuCartFormat['sku_id']] = $tempList;
                        }


                        //SKU排序用
                        $skuAddTimeSort[] = $cartSku['addtime_stamp'];

                        $sku_list[] = $skuCartFormat;
                    }

                    //
                    if (!$isReturn) {
                        continue;
                    }
                    //购物车店铺优惠券计算  小程序不可用
                    if (version_compare(HhzClient::getClientVersion(), '3.6.0', '>=')) {
                        if (isset($shopSkuBuyList) && $uid > 0 && !$isParagraph && !$isMini) {
                            $couponSelect = clsShopCoupon::getBestShopCouponSelect($uid, $shopId, $shopSkuBuyList);
                            if (!empty($couponSelect)) {
                                $shopCouponSelect[] = $couponSelect;
                                //店铺最值优惠券拿到后开始计算剩余的商品购买额
                                $result = clsShopCoupon::calOrderSkuCouponDiscount($uid, $couponSelect['coupon_id'], $couponSelect['detract_amount'], '', $shopSkuBuyList);
                                if (!empty($result)) {
                                    foreach ($skuBuyList as $skuId => &$skuBuyInfo) {
                                        if (isset($result[$skuId])) {
                                            $skuBuyInfo['total_amount'] = ($skuBuyInfo['buy_num'] * $skuBuyInfo['buy_price']) - $result[$skuId]['coupon_discount'];
                                        }
                                    }
                                }
                                $detract_amount = $couponSelect['detract_amount'];
                                //总额递减
                                $summary['goods_amount'] = $summary['goods_amount'] - $detract_amount;
                                $goods_amount = $goods_amount - $detract_amount;
                                $s_coupon_amount = $s_coupon_amount + $detract_amount;
                            }
                        }
                    }

                    //计算店铺中商品购买的运费
                    if (!empty($shippingPriceParams)) {
                        $shippingPrice = sShippingTempl::getShippingFee($shopId, $shippingPriceParams, $areaCode);
                        $summary['shipping_price'] = $shippingPrice['price'];
                    }

                    //商品按照sku添加到购物车的时间倒序
                    $sort_near_addtime = 0;
                    if (!empty($skuAddTimeSort)) {
                        array_multisort($skuAddTimeSort, SORT_DESC, $sku_list);
                        rsort($skuAddTimeSort);
                        $sort_near_addtime = $skuAddTimeSort[0];
                    }
                    if (!empty($sku_list)) {
                        //商品tip信息
                        sTipInfo::skuInCart($sku_list);

                        //商品套餐信息
                        sTipInfo::mealTip($sku_list);

                        //收货地址限制提示
                        sTipInfo::areaTip($sku_list, $areaCode);

                        //团购提示
                        sTipInfo::groupTip($sku_list, $groupMap);
                    }


                    //查询满包邮活动的商品
                    $goods_ids = array_column($sku_list, 'goods_id');
                    $shippingMap = FullShipping::FullShippingMap($shopId, $areaCode, $goods_ids);
                    $shopShippingMap[$shopId] = $shippingMap;
                    $map = $shippingMap['map'];
                    $shippingTotal = $shippingMap['total'];
                    $shippingType = $shippingMap['type'];
                    $shippingDetail = $shippingMap['detail'];
                    $activityTip = $shippingType == mFullShipping::TYPE_TOTAL_AMOUNT ? "以上商品参与满包邮活动，满%s元即可包邮" : "以上商品参与满包邮活动，满%s件即可包邮";
                    foreach ($sku_list as $v) {
                        $goodsIconMap = isset($active_icon_map[$v['goods_id']]) ? $active_icon_map[$v['goods_id']] : [];
                        $v['active_icon_list'] = $this->formatActiveIconMap($goodsIconMap, $v['activity_type']);
                        Log::debug('购物车列表来源cartListVersion debug' . $v['goods_id'], compact('v', 'goodsIconMap'));
                        if (in_array($v['goods_id'], $map)) {
                            if (in_array($v['sku_id'], $selectSkuIds)) {
                                if ($shippingType == mFullShipping::TYPE_TOTAL_AMOUNT) {
                                    $shippingTotal = bcsub($shippingTotal, $v['buy_num'] * $v['buy_price'], 2);
                                } else {
                                    $shippingTotal = bcsub($shippingTotal, $v['buy_num'], 0);
                                }
                                $activityTip = $shippingType == mFullShipping::TYPE_TOTAL_AMOUNT ? "以上商品参与满包邮活动，还差%s元可包邮" : "以上商品参与满包邮活动，还差%s件可包邮";
                            }
                            //以上商品参与满包邮活动，满xx元即可包邮     以上商品参与满包邮活动，还差xx元可包邮  商品已包邮
                            //以上商品参与满包邮活动，满X件即可包邮     以上商品参与满包邮活动，还差x件可包邮
                            $shippingDetail['activityId'] = "fullShipping";
                            $shippingDetail['activityTip'] = $shippingTotal > 0 ? sprintf($activityTip, $shippingTotal) : "商品已包邮";
                            $activity_sku_list['full']['activityInfo'] = $shippingDetail;
                            $activity_sku_list['full']['sku_list'][] = $v;
                        } else {
                            $activity_sku_list['normal']['sku_list'][] = $v;
                        }
                    }
                    ksort($activity_sku_list);
                    $activity_sku_list = array_values($activity_sku_list);

                    //格式化数据
                    $summary['goods_amount'] = toolAmount::format($summary['goods_amount']);
                    $responseList[] = compact('summary', 'shop_info', 'coupon_info', 'activity_sku_list', 'sort_near_addtime');
                }

                //格式化数据
                $s_coupon_amount = Amount::format($s_coupon_amount);

                if (!empty($responseList)) {
                    //商家tip信息
//                    sTipInfo::shopInCart($responseList, $areaCode, $isSelect);
                    //商家按照sku添加到购物车的时间倒序
                    array_walk($responseList, function (&$v) use (&$skuAddTimeShopSort) {
                        $skuAddTimeShopSort[] = $v['sort_near_addtime'];
                        unset($v['sort_near_addtime']);
                    });
                    array_multisort($skuAddTimeShopSort, SORT_DESC, $responseList);
                }

                //购物车平台优惠券计算  小程序不可用
                $platformDataBuyList = [];
                if (version_compare(HhzClient::getClientVersion(), '3.5.2', '>=')) {
                    if (isset($skuBuyList) && $uid > 0 && !$isParagraph && !$isMini) {
                        foreach ($skuBuyList as $skuId => $buyList) {
                            $platformDataBuyList[$skuId] = $buyList;
                        }

                        $platformCouponSelect = clsCoupon::getBestCouponSelect($uid, $platformDataBuyList);
                        if (!empty($platformCouponSelect)) {
                            //优惠总额递减
                            $goods_amount = $goods_amount - $platformCouponSelect['detract_amount'];
                            $coupon = [
                                'coupon_vid' => $platformCouponSelect['coupon_vid'],
                                'coupon_id' => $platformCouponSelect['coupon_id'],
                                'title' => $platformCouponSelect['title'],
                                'detract_amount' => $platformCouponSelect['detract_amount'],
                            ];
                        }
                        $promo = sCoupon::recommendPromo($selectSkuIds, $uid, $areaCode, $appSource, $appType);
                        $coupon['promoType'] = isset($promo['type']) ? $promo['type'] : '0';
                        $coupon['tip'] = isset($promo['promo']) ? $promo['promo'] : '';
                    }
                }

                //格式化保留两位小数
                $goods_amount = Amount::format($goods_amount);
            }
        }

        if ($isSelect) {
            unset($response['fail']);
        }
        self::info_log('购物车列表信息cartListVersion', compact('groupMap'));
//        ActionLog::log($uid, ['nowtime' => date('Y-m-d H:i:s'),'appSource' => $appSource, 'skuIds' => $skuIds, 'areaCode' => $areaCode], ActionLog::BIZ_CART_LIST);
        return $response;
    }

    private function formatActiveIconMap($iconList, $checkActiveType)
    {
        $icons = [];
        foreach ($iconList as $activeType => $value) {
            if (in_array($activeType, ActivityInfo::SKU_CHECK_MAP)) {
                if ($checkActiveType == $activeType) {
                    $icons[] = $value;
                }
            } else {
                $icons[] = $value;
            }
        }
        return array_slice($icons, 0, 2);
    }

    /**
     * 购物车列表
     * @param int $uid 用户/游客id
     * @param array $skuIds 货品id集合
     * @param string $areaCode 地区编码
     * @param int $appSource app来源
     * @param int $appType app类型
     * @return mixed
     * @throws \Exception
     */
    public function cartList($uid, $skuIds = [], $areaCode = '', $appSource = 0, $appType = 0)
    {
        //初始化返回结果
        $data = [
            'summary' => [
                'goods_amount' => 0,
                'total_buynum' => 0,
                's_coupon_amount' => 0,//店铺优惠券最大抵扣金额
            ],
            'list' => [],
            'fail' => [],
            'coupon' => null,
        ];

        //判断是否是手选
        $isSelect = !empty($skuIds) ? true : false;

        //拿失效的购物车数据
        $failList = $this->getCartFailList($uid, $skuIds, true, $appSource);

        if (!empty($failList)) {
            foreach ($failList as $skuId => $cartSku) {
                //实时观察失效商品SKU，如果变成有效的，则rollback 到有效列表
                $result = $this->toggleStatus($uid, $cartSku['sku_info'], $appSource);
                if ($result) {
                    continue;
                }
                $data['fail'][] = $this->formatFailCartSku($cartSku);
            }
        }

        //拿有效的购物车数据
        $cartList = $this->getCartActiveList($uid, $skuIds, true, $appSource);

        if (!empty($cartList)) {
            $allGoodsIds = [];
            //购物车商品结构组装
            foreach ($cartList as $shopId => $cartSkuList) {
                //购物车商家总信息
                $data['list'][$shopId]['summary'] = [
                    'goods_amount' => 0,
                    'shipping_price' => 0,
                ];
                $shopInfo = sShopInfo::getShopInfo($shopId, ['user']);
                //店铺基本信息结构
                $data['list'][$shopId]['shop_info'] = [
                    'shop_id' => $shopInfo['shop_id'],
                    'shop_name' => $shopInfo['shop_name'],
                    'status' => $shopInfo['status'],
                    'imgurl' => $shopInfo['shop_imgurl_small'],
                    'shop_icon' => $shopInfo['shop_imgurl_small'],
                ];

                //店铺是否有优惠券结构
                $data['list'][$shopId]['coupon_info'] = [
                    'has_coupon' => clsShopCoupon::checkShopHasCoupon($shopInfo['shop_id']),
                ];
                $goods_ids = $cartSkuList ? array_column($cartSkuList, 'goods_id') : [];
                $allGoodsIds = array_merge($allGoodsIds, $goods_ids);
                //获取活动标签
                $goods = Goods::Goods($goods_ids, Goods::FIELDS_GROUP_PARAGRAPH_CART);
                $active_icon_map = $goods ? array_column($goods, 'active_icon_list', 'id') : [];

                foreach ($cartSkuList as $cartSku) {
                    //实时观察失效商品SKU
                    $result = $this->toggleStatus($uid, $cartSku['sku_info'], $appSource, 0);
                    if ($result) {
                        $data['fail'][] = $this->formatFailCartSku($cartSku);
                        continue;
                    }
                    $goodsIconMap = isset($active_icon_map[$cartSku['goods_id']]) ? $active_icon_map[$cartSku['goods_id']] : [];
                    $cartSku['active_icon_list'] = $this->formatActiveIconMap($goodsIconMap, $cartSku['sku_info']['activity_type']);
                    $data['list'][$shopId]['sku_list'][] = $cartSku;
                }
                if (empty($data['list'][$shopId]['sku_list'])) {
                    unset($data['list'][$shopId]);
                }
            }
            $groupMap = PinTuan::getCurrentList($allGoodsIds);
            if (!empty($data['list'])) {
                $this->formatCartList($uid, $data, $isSelect, $areaCode, $appSource, $appType, $groupMap);
            }
        }
        self::info_log('购物车列表信息cartList', compact('groupMap', 'allGoodsIds'));

        ActionLog::log($uid, ['nowtime' => date('Y-m-d H:i:s'), 'appSource' => $appSource, 'appType' => $appType, 'skuIds' => $skuIds, 'areaCode' => $areaCode], ActionLog::BIZ_CART_LIST);

        return $data;
    }

    public function cartListVersion461($uid, $selectSkuIds = [], $areaCode = '', $appSource = 0, $appType = 0)
    {
        //debug
        $shopShippingMap = [];
        $shopCouponSelect = [];
        $platformCouponSelect = [];
        $skuBuyList = [];
        //初始化返回结果
        $goods_amount = 0;
        $total_buynum = 0;
        $s_coupon_amount = 0;
        $fail = [];
        $responseList = [
            [
                'summary' => [
                    'goods_amount' => 0,
                    'shipping_price' => 0,
                ],
                'shop_info' => [

                ],
                'coupon_info' => [

                ],
                'sku_list' => [

                ],
            ],
        ];
        $coupon = null;
        $response = [
            'new' => HhzClient::getClientVersion(),
            'summary' => [
                'goods_amount' => &$goods_amount,
                'total_buynum' => &$total_buynum,
                's_coupon_amount' => &$s_coupon_amount,//店铺优惠券最大抵扣金额
            ],
            'list' => &$responseList,
            'fail' => &$fail,
            'coupon' => &$coupon,
        ];

        //判断是否是手选
        $isSelect = !empty($selectSkuIds) ? true : false;
        //获取有效/失效的购物车数据
        $failStatus = $this->getCartFailStatus();
        $activeStatus = $this->getCartActiveStatus();
        $list = $this->getCartListMain($uid, [$failStatus, $activeStatus], [], $appSource);
        $sku_ids = $list ? array_column($list, 'sku_id') : [];
        $goods_ids = $list ? array_column($list, 'goods_id') : [];
        $statusMap = $list ? array_column($list, 'status', 'sku_id') : [];

        //商品详情
        $skuInfoList = sSku::Sku4Order($sku_ids);
        $goods = Goods::Goods($goods_ids, Goods::FIELDS_GROUP_CART);
        $active_icon_map = $goods ? array_column($goods, 'active_icon_list', 'id') : [];

        $responseList = [];
        if (!empty($list)) {
            $activeList = [];
            foreach ($list as $cartSku) {
                $sku_id = $cartSku['sku_id'];
                $skuInfo = isset($skuInfoList[$sku_id]) ? $skuInfoList[$sku_id] : [];
                $initialStatus = isset($statusMap[$sku_id]) ? $statusMap[$sku_id] : $failStatus;
                $shopId = isset($skuInfo['shop_id']) ? $skuInfo['shop_id'] : 0;

                //实时观察失效商品SKU，如果变成有效的，则rollback 到有效列表
                $flag = $initialStatus == $activeStatus ? 0 : 1;
                $toggle = $this->toggleStatus461($uid, $skuInfo, $appSource, $flag);

                $activeBool = $initialStatus == $activeStatus && !$toggle;//有效商品,没有变化
                $failBool = $initialStatus == $failStatus && $toggle;//失效商品,有变化
                if ($activeBool || $failBool) {
                    //购物车有效数据,按店铺进行分组
                    $this->formatInfo($cartSku);
                    if (isset($skuInfoList) && isset($skuInfoList[$sku_id])) {
                        $cartSku['sku_info'] = $skuInfoList[$sku_id];
                    }
                    $activeList[$shopId][] = $cartSku;
                } else {
                    $fail[] = $this->formatFailCartSku($cartSku);
                }
            }

            //处理购物车有效数据
            if ($activeList) {
                $isParagraph = $appSource == AppType::APPTYPE_PARAGRAPH_MINIPROGRAM;//节选标识
                $isMini = $appType == AppType::APPTYPE_MINIPROGRAM;//小程序
                foreach ($activeList as $shopId => $shopGoods) {
                    //购物车商家总信息
                    $summary = [
                        'goods_amount' => 0,
                        'shipping_price' => 0,
                    ];
                    $shopInfo = sShopInfo::getShopInfo($shopId, ['user']);

                    //店铺基本信息结构
                    $shop_info = [
                        'shop_id' => $shopInfo['shop_id'],
                        'shop_name' => $shopInfo['shop_name'],
                        'status' => $shopInfo['status'],
                        'imgurl' => $shopInfo['shop_imgurl_small'],
                        'shop_icon' => $shopInfo['shop_imgurl_small'],
                    ];

                    //店铺是否有优惠券结构
                    $coupon_info = [
                        'has_coupon' => clsShopCoupon::checkShopHasCoupon($shopId),
                    ];

                    //店铺商品列表
                    $sku_list = [];
                    $activity_sku_list = [];
                    $shopSkuBuyList = [];
                    $skuAddTimeSort = [];
                    $shippingPriceParams = [];

                    if (empty($selectSkuIds)) {
                        $isReturn = true;
                    } else {
                        $isReturn = false;
                    }
                    foreach ($shopGoods as $cartSku) {
                        $skuCartFormat = $this->formatActiveSkuInfo($cartSku);

                        //计算购物车总信息
                        if (in_array($cartSku['sku_id'], $selectSkuIds)) {
                            $isReturn = true;
                            $total_buynum += $cartSku['buy_num'];
                            $goods_amount += $skuCartFormat['buy_price'] * $cartSku['buy_num'];

                            //计算店铺中商品购买的运费使用
                            if (isset($shippingPriceParams[$cartSku['goods_id']][$cartSku['sku_id']])) {
                                $shippingPriceParams[$cartSku['goods_id']][$cartSku['sku_id']]['buy_num'] += $cartSku['buy_num'];
                                $shippingPriceParams[$cartSku['goods_id']][$cartSku['sku_id']]['weight'] += $cartSku['sku_info']['weight'];
                                $shippingPriceParams[$cartSku['goods_id']][$cartSku['sku_id']]['volume'] += $cartSku['sku_info']['volume'];
                            } else {
                                $shippingPriceParams[$cartSku['goods_id']][$cartSku['sku_id']]['shipping_templ_id'] = $cartSku['sku_info']['goods_info']['shipping_templ_id'];
                                $shippingPriceParams[$cartSku['goods_id']][$cartSku['sku_id']]['buy_num'] = $cartSku['buy_num'];
                                $shippingPriceParams[$cartSku['goods_id']][$cartSku['sku_id']]['weight'] = $cartSku['sku_info']['weight'];
                                $shippingPriceParams[$cartSku['goods_id']][$cartSku['sku_id']]['volume'] = $cartSku['sku_info']['volume'];
                            }


                            //计算购物车中商家总信息
                            $summary['goods_amount'] += $skuCartFormat['buy_price'] * $cartSku['buy_num'];

                            //计算优惠券优惠使用
                            $tempList = [
                                'goods_id' => $skuCartFormat['goods_id'],
                                'buy_price' => $skuCartFormat['buy_price'],
                                'buy_num' => $cartSku['buy_num']
                            ];
                            $skuBuyList[$skuCartFormat['sku_id']] = $tempList;
                            $shopSkuBuyList[$skuCartFormat['sku_id']] = $tempList;
                        }


                        //SKU排序用
                        $skuAddTimeSort[] = $cartSku['addtime_stamp'];

                        $sku_list[] = $skuCartFormat;
                    }

                    //
                    if (!$isReturn) {
                        continue;
                    }
                    //购物车店铺优惠券计算  小程序不可用
                    if (version_compare(HhzClient::getClientVersion(), '3.6.0', '>=')) {
                        if (isset($shopSkuBuyList) && $uid > 0 && !$isParagraph && !$isMini) {
                            $couponSelect = clsShopCoupon::getBestShopCouponSelect($uid, $shopId, $shopSkuBuyList);
                            if (!empty($couponSelect)) {
                                $shopCouponSelect[] = $couponSelect;
                                //店铺最值优惠券拿到后开始计算剩余的商品购买额
                                $result = clsShopCoupon::calOrderSkuCouponDiscount($uid, $couponSelect['coupon_id'], $couponSelect['detract_amount'], '', $shopSkuBuyList);
                                if (!empty($result)) {
                                    foreach ($skuBuyList as $skuId => &$skuBuyInfo) {
                                        if (isset($result[$skuId])) {
                                            $skuBuyInfo['total_amount'] = ($skuBuyInfo['buy_num'] * $skuBuyInfo['buy_price']) - $result[$skuId]['coupon_discount'];
                                        }
                                    }
                                }
                                $detract_amount = $couponSelect['detract_amount'];
                                //总额递减
                                $summary['goods_amount'] = $summary['goods_amount'] - $detract_amount;
                                $goods_amount = $goods_amount - $detract_amount;
                                $s_coupon_amount = $s_coupon_amount + $detract_amount;
                            }
                        }
                    }

                    //计算店铺中商品购买的运费
                    if (!empty($shippingPriceParams)) {
                        $shippingPrice = sShippingTempl::getShippingFee($shopId, $shippingPriceParams, $areaCode);
                        $summary['shipping_price'] = $shippingPrice['price'];
                    }

                    //商品按照sku添加到购物车的时间倒序
                    $sort_near_addtime = 0;
                    if (!empty($skuAddTimeSort)) {
                        array_multisort($skuAddTimeSort, SORT_DESC, $sku_list);
                        rsort($skuAddTimeSort);
                        $sort_near_addtime = $skuAddTimeSort[0];
                    }
                    if (!empty($sku_list)) {
                        //商品tip信息
                        sTipInfo::skuInCart($sku_list);

                        //商品套餐信息
                        sTipInfo::mealTip($sku_list);

                        //收货地址限制提示
                        sTipInfo::areaTip($sku_list, $areaCode);

                    }


                    //查询满包邮活动的商品
                    $goods_ids = array_column($sku_list, 'goods_id');
                    $shippingMap = FullShipping::FullShippingMap($shopId, $areaCode, $goods_ids);
                    $shopShippingMap[$shopId] = $shippingMap;
                    $map = $shippingMap['map'];
                    $shippingTotal = $shippingMap['total'];
                    $shippingType = $shippingMap['type'];
                    $shippingDetail = $shippingMap['detail'];
                    $activityTip = $shippingType == mFullShipping::TYPE_TOTAL_AMOUNT ? "以上商品参与满包邮活动，满%s元即可包邮" : "以上商品参与满包邮活动，满%s件即可包邮";
                    foreach ($sku_list as $v) {
                        $goodsIconMap = isset($active_icon_map[$v['goods_id']]) ? $active_icon_map[$v['goods_id']] : [];
                        $v['active_icon_list'] = $this->formatActiveIconMap($goodsIconMap, $v['activity_type']);
                        Log::debug('购物车列表来源cartListVersion debug' . $v['goods_id'], compact('v', 'goodsIconMap'));
                        if (in_array($v['goods_id'], $map)) {
                            if (in_array($v['sku_id'], $selectSkuIds)) {
                                if ($shippingType == mFullShipping::TYPE_TOTAL_AMOUNT) {
                                    $shippingTotal = bcsub($shippingTotal, $v['buy_num'] * $v['buy_price'], 2);
                                } else {
                                    $shippingTotal = bcsub($shippingTotal, $v['buy_num'], 0);
                                }
                                $activityTip = $shippingType == mFullShipping::TYPE_TOTAL_AMOUNT ? "以上商品参与满包邮活动，还差%s元可包邮" : "以上商品参与满包邮活动，还差%s件可包邮";
                            }
                            //以上商品参与满包邮活动，满xx元即可包邮     以上商品参与满包邮活动，还差xx元可包邮  商品已包邮
                            //以上商品参与满包邮活动，满X件即可包邮     以上商品参与满包邮活动，还差x件可包邮
                            $shippingDetail['activityId'] = "fullShipping";
                            $shippingDetail['activityTip'] = $shippingTotal > 0 ? sprintf($activityTip, $shippingTotal) : "商品已包邮";
                            $activity_sku_list['full']['activityInfo'] = $shippingDetail;
                            $activity_sku_list['full']['sku_list'][] = $v;
                        } else {
                            $activity_sku_list['normal']['sku_list'][] = $v;
                        }
                    }
                    ksort($activity_sku_list);

                    $activity_sku_list = array_values($activity_sku_list);

                    //格式化数据
                    $summary['goods_amount'] = toolAmount::format($summary['goods_amount']);
                    $responseList[] = compact('summary', 'shop_info', 'coupon_info', 'activity_sku_list', 'sort_near_addtime');
                }

                //格式化数据
                $s_coupon_amount = Amount::format($s_coupon_amount);

                if (!empty($responseList)) {
                    //商家tip信息
//                    sTipInfo::shopInCart($responseList, $areaCode, $isSelect);
                    //商家按照sku添加到购物车的时间倒序
                    array_walk($responseList, function (&$v) use (&$skuAddTimeShopSort) {
                        $skuAddTimeShopSort[] = $v['sort_near_addtime'];
                        unset($v['sort_near_addtime']);
                    });
                    array_multisort($skuAddTimeShopSort, SORT_DESC, $responseList);
                }

                //购物车平台优惠券计算  小程序不可用
                $platformDataBuyList = [];
                if (version_compare(HhzClient::getClientVersion(), '3.5.2', '>=')) {
                    if (isset($skuBuyList) && $uid > 0 && !$isParagraph && !$isMini) {
                        foreach ($skuBuyList as $skuId => $buyList) {
                            $platformDataBuyList[$skuId] = $buyList;
                        }

                        $platformCouponSelect = clsCoupon::getBestCouponSelect($uid, $platformDataBuyList);
                        if (!empty($platformCouponSelect)) {
                            //优惠总额递减
                            $goods_amount = $goods_amount - $platformCouponSelect['detract_amount'];
                            $coupon = [
                                'coupon_vid' => $platformCouponSelect['coupon_vid'],
                                'coupon_id' => $platformCouponSelect['coupon_id'],
                                'title' => $platformCouponSelect['title'],
                                'detract_amount' => $platformCouponSelect['detract_amount'],
                            ];
                        }
                        $promo = sCoupon::recommendPromo($selectSkuIds, $uid, $areaCode, $appSource, $appType);
                        $coupon['promoType'] = isset($promo['type']) ? $promo['type'] : '0';
                        $coupon['tip'] = isset($promo['promo']) ? $promo['promo'] : '';
                    }
                }

                //格式化保留两位小数
                $goods_amount = Amount::format($goods_amount);
            }
        }

        if ($isSelect) {
            unset($response['fail']);
        }
        self::info_log('购物车列表信息cartListVersion', compact('groupMap'));
//        ActionLog::log($uid, ['nowtime' => date('Y-m-d H:i:s'),'appSource' => $appSource, 'skuIds' => $skuIds, 'areaCode' => $areaCode], ActionLog::BIZ_CART_LIST);
        return $response;
    }


    /**
     * 切换购物车有效与失效的状态
     * @param int $uid 游客id
     * @param array $skuInfo 货品信息
     * @param int $appSource app来源
     * @param int $flag 1 变为有效 0 变为失效
     * @return mixed
     * @throws \Exception
     */
    protected function toggleStatus461($uid, $skuInfo, $appSource, $flag = 1)
    {
        try {
            $this->isFailSku($skuInfo);
            $isFail = false;
            $message = '';
        } catch (\Exception $e) {
            $isFail = true;
            $message = $e->getMessage();
        }

        $isChange = false;
        $status = null;
        $title = null;
        if ($flag > 0 && $isFail == false) {
            $status = $this->getCartActiveStatus();
            $title = '购物车SKU由失效变为有效';
            $isChange = true;
        }
        if ($flag == 0 && $isFail == true) {
            $status = $this->getCartFailStatus();
            $title = '购物车SKU由有效变为失效,原因:' . $message;
            $isChange = true;
        }

        if ($isChange) {
            return true;
            $data = $this->modifyCart(['status' => $status], ['uid' => $uid, 'sku_id' => $skuInfo['sku_id'], 'app_source' => $appSource]);
            self::info_log($title, ['uid' => $uid, 'sku_id' => $skuInfo['sku_id'], 'app_source' => $appSource, 'sku_info' => $skuInfo]);

            if ($data->rowCount() == 1) {
                return true;
            }
        }
        return false;
    }


}